<?php

namespace App\Http\Traits;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Query\Expression;
use Illuminate\Http\Request;

trait QueryHelperTrait
{
    public static function buildWhereClause(Builder $query, array $searchFields, string $searchText) {
        foreach ($searchFields as $i => $field) {
            if ($field instanceof Expression) {
                $field = $field->getValue();
                if ($i == 0) $query->whereRaw("$field = ?", [$searchText]);
                $query->orWhereRaw("$field = ?", [$searchText]);
            } else {
                if ($i == 0) $query->where($field, 'LIKE', "%$searchText%");
                $query->orWhere($field, 'LIKE', "%$searchText%");
            }
        }
    }

    public static function pagination(Builder $query, Request $request, $extraSelectFields = []) {
        $model = get_called_class();
        $tableName = with(new $model)->getTable();

        $query->select(array_merge([$tableName . '.*'], $extraSelectFields));
        $query->orderBy($request->input('column', $tableName . '.created_at'), $request->input('direction', 'desc'));
        return $query->paginate($request->input('perPage', 25));
    }
}
